import { querySectionsByTagGroup } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type { ISection, ITagGroup } from '@/interfaces';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';

export default function QueryTagGroupSections({
  details,
}: {
  details: ITagGroup;
}) {
  const querySectionsByTagGroupQuery = useQuery(
    ['/forum', '/tagGroups', details.id, '/sections'],
    async (context) => {
      return (await querySectionsByTagGroup({
        id: context.queryKey[2] + '',
      })) as ISection[];
    },
  );

  if (querySectionsByTagGroupQuery.data) {
    const data = querySectionsByTagGroupQuery.data;

    return (
      <div className="row">
        <div className="col">
          <div className="card">
            <div className="card-header bg-transparent text-muted">
              <i className="bi bi-list me-2"></i>
              版块
            </div>
            <div className="card-body">
              <div className="table-responsive">
                <table className="table table-hover align-middle">
                  <thead>
                    <tr className="text-nowrap">
                      <th scope="col" className="w-10 fw-normal">
                        ID
                      </th>
                      <th scope="col" className="w-10 fw-normal">
                        名称
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.map((item) => {
                      return (
                        <tr key={item.id} className="text-nowrap">
                          <td>{item.id}</td>
                          <td>{item.name}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>

                {data.length === 0 && (
                  <div className="text-center text-muted">暂无版块</div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (querySectionsByTagGroupQuery.error) {
    return <Alert message={querySectionsByTagGroupQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
